import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import '../controllers/home_controller.dart';
import '../../../utils/screen_adapter.dart';
import '../../../config/app_constants.dart';

class HomeView extends GetView<HomeController> {
  const HomeView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            _buildToolbar(),
            Expanded(
              child: Obx(() => _buildWebViewContent()),
            ),
          ],
        ),
      ),
    );
  }

  // 构建工具栏
  Widget _buildToolbar() {
    return Container(
      height: 56.h,
      padding: ScreenAdapter.padding(horizontal: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 4.r,
            offset: Offset(0, 2.h),
          ),
        ],
      ),
      child: Row(
        children: [
          // 后退按钮
          Obx(
            () => IconButton(
              onPressed: controller.canGoBack.value ? controller.goBack : null,
              icon: Icon(
                Icons.arrow_back_ios,
                size: 20.r,
                color: controller.canGoBack.value
                    ? const Color(0xFF4CAF50)
                    : Colors.grey,
              ),
            ),
          ),

          // 前进按钮
          Obx(
            () => IconButton(
              onPressed:
                  controller.canGoForward.value ? controller.goForward : null,
              icon: Icon(
                Icons.arrow_forward_ios,
                size: 20.r,
                color: controller.canGoForward.value
                    ? const Color(0xFF4CAF50)
                    : Colors.grey,
              ),
            ),
          ),

          // 页面标题
          Expanded(
            child: Obx(
              () => Text(
                controller.pageTitle.value.isNotEmpty
                    ? controller.pageTitle.value
                    : '首页',
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                  color: const Color(0xFF333333),
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),

          // 刷新按钮
          IconButton(
            onPressed: controller.refresh,
            icon: Icon(
              Icons.refresh,
              size: 24.r,
              color: const Color(0xFF4CAF50),
            ),
          ),
        ],
      ),
    );
  }

  // 构建WebView内容
  Widget _buildWebViewContent() {
    if (controller.hasError.value) {
      return _buildErrorView();
    }

    return _buildWebView();
  }

  // 构建WebView
  Widget _buildWebView() {
    return InAppWebView(
      initialUrlRequest: URLRequest(
        url: WebUri(controller.mainController.currentWikiUrl.value),
      ),
      initialSettings: InAppWebViewSettings(
        userAgent: AppConstants.webViewUserAgent,
        javaScriptEnabled: AppConstants.webViewJavaScriptEnabled,
        domStorageEnabled: AppConstants.webViewDomStorageEnabled,
        supportZoom: true,
        builtInZoomControls: true,
        displayZoomControls: false,
        useWideViewPort: true,
        loadWithOverviewMode: true,
        mixedContentMode: MixedContentMode.MIXED_CONTENT_COMPATIBILITY_MODE,
        allowsInlineMediaPlayback: true,
        mediaPlaybackRequiresUserGesture: false,
        verticalScrollBarEnabled: true,
        horizontalScrollBarEnabled: true,
        disableVerticalScroll: false,
        disableHorizontalScroll: false,
        transparentBackground: false,
        cacheEnabled: true,
        clearCache: false,
        useShouldOverrideUrlLoading: true,
      ),
      onWebViewCreated: controller.onWebViewCreated,
      onLoadStart: controller.onLoadStart,
      onLoadStop: controller.onLoadStop,
      onProgressChanged: controller.onProgressChanged,
      onTitleChanged: controller.onTitleChanged,
      // onLoadError: controller.onLoadError,
      // onLoadHttpError: (controller, url, statusCode, description) {
      //   this.controller.onLoadError(controller, url, statusCode, description);
      // },
      shouldOverrideUrlLoading: (controller, navigationAction) async {
        final uri = navigationAction.request.url;

        // 允许在同一个WebView中打开链接
        if (uri != null) {
          final url = uri.toString();

          // 检查是否为外部链接
          if (url.startsWith('http://') || url.startsWith('https://')) {
            // 如果是Wiki相关链接，在当前WebView中打开
            if (url.contains('wiki') ||
                url.contains('fandom') ||
                url.contains('stardewvalley')) {
              return NavigationActionPolicy.ALLOW;
            }
          }
        }

        return NavigationActionPolicy.ALLOW;
      },
    );
  }

  // 构建错误视图
  Widget _buildErrorView() {
    return Container(
      padding: ScreenAdapter.padding(all: 32),
      child: Column(
        mainAxisSize: MainAxisSize.min, // 防止溢出
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.error_outline,
            size: 64.r,
            color: Colors.red[400],
          ),
          SizedBox(height: 24.h),
          Text(
            '页面加载失败',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: const Color(0xFF333333),
            ),
          ),
          SizedBox(height: 12.h),
          Text(
            controller.errorMessage.value,
            style: TextStyle(
              fontSize: 14.sp,
              color: const Color(0xFF666666),
            ),
            textAlign: TextAlign.center,
          ),
          SizedBox(height: 32.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              ElevatedButton.icon(
                onPressed: controller.refresh,
                icon: Icon(Icons.refresh, size: 18.r),
                label: const Text('重新加载'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF4CAF50),
                  foregroundColor: Colors.white,
                  padding: ScreenAdapter.padding(horizontal: 24, vertical: 12),
                  shape: RoundedRectangleBorder(
                    borderRadius: ScreenAdapter.borderRadius(all: 8),
                  ),
                ),
              ),
              OutlinedButton.icon(
                onPressed: () {
                  controller.loadUrl(AppConstants.defaultWikiUrl);
                },
                icon: Icon(Icons.home, size: 18.r),
                label: const Text('返回首页'),
                style: OutlinedButton.styleFrom(
                  foregroundColor: const Color(0xFF4CAF50),
                  side: const BorderSide(color: Color(0xFF4CAF50)),
                  padding: ScreenAdapter.padding(horizontal: 24, vertical: 12),
                  shape: RoundedRectangleBorder(
                    borderRadius: ScreenAdapter.borderRadius(all: 8),
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
